package com.imooc.article.html.controller;

import com.imooc.api.controller.article.ArticleHtmlControllerApi;
import com.imooc.api.controller.user.BaseControllerApi;
import com.mongodb.client.gridfs.GridFSBucket;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * @Project_name: imooc-news-dev
 * @Description:
 * @Author: Levi
 * @Date: 2021/3/28 21:40
 */
@RestController
public class ArticleHtmlController  implements ArticleHtmlControllerApi {

    @Autowired
    public GridFSBucket gridFSBucket;

    @Value("${freemarker.html.path}")
    public String filePath;


    @Override
    public Integer download(String articleId, String articleMongoId) throws Exception {
        //1.创建文件对象
        File file = new File(filePath+File.separator+articleId+".html");
        //2.创建文件输出流
        OutputStream out = new FileOutputStream(file);
        //3.下载文件
        gridFSBucket.downloadToStream(new ObjectId(articleMongoId),out);
        out.close();
        return HttpStatus.OK.value();
    }

    @Transactional
    @Override
    public Integer deleteGridFSAndHtml(String articleId) {
        File file = new File(filePath+File.separator+articleId+".html");
        if (file.exists()) {
            boolean result = file.delete();
            System.out.println(result);
        }
        return HttpStatus.OK.value();
    }
}
